package com.ruoyi.common.config;

import com.fasterxml.jackson.core.JsonGenerator;
import com.fasterxml.jackson.databind.*;
import com.fasterxml.jackson.databind.module.SimpleModule;
import com.fasterxml.jackson.databind.ser.std.ToStringSerializer;
import com.fasterxml.jackson.datatype.jsr310.ser.LocalDateTimeSerializer;
import org.springframework.beans.factory.annotation.Value;
import org.springframework.boot.autoconfigure.AutoConfigureBefore;
import org.springframework.boot.autoconfigure.jackson.Jackson2ObjectMapperBuilderCustomizer;
import org.springframework.boot.autoconfigure.jackson.JacksonAutoConfiguration;
import org.springframework.context.annotation.Bean;
import org.springframework.context.annotation.Configuration;
import org.springframework.context.annotation.Primary;
import org.springframework.http.converter.json.Jackson2ObjectMapperBuilder;

import java.io.IOException;
import java.math.BigDecimal;
import java.text.DateFormat;
import java.text.SimpleDateFormat;
import java.time.LocalDateTime;
import java.time.format.DateTimeFormatter;
import java.util.TimeZone;

/**
 * @Program: socializeMicroApi
 * @ClassName: JacksonConfig
 * @author: zhouzihao
 * @date: 2023年10月16日, 0016 下午 01:51:42
 * @version: 1.0.0
 * @Description:
 * @Time： 2023-10-16 13:51
 */
@Configuration
@AutoConfigureBefore(JacksonAutoConfiguration.class)
public class JacksonConfig {

    @Value("${spring.jackson.date-format:yyyy-MM-dd HH:mm:ss}")
    private String pattern;

    /**
     * @author xiaofu
     * @description date 类型全局时间格式化
     * @date 2020/8/31 18:22
     */
    @Bean
    public Jackson2ObjectMapperBuilderCustomizer jackson2ObjectMapperBuilder() {

        return builder -> {
            TimeZone tz = TimeZone.getTimeZone("GMT+8");
            DateFormat df = new SimpleDateFormat(pattern);
            df.setTimeZone(tz);
            builder.failOnEmptyBeans(false).failOnUnknownProperties(false).featuresToDisable(SerializationFeature.WRITE_DATES_AS_TIMESTAMPS).dateFormat(df);
            builder.serializerByType(LocalDateTime.class, localDateTimeDeserializer());
        };
    }

    /**
     * @author xiaofu
     * @description LocalDate 类型全局时间格式化
     * @date 2020/8/31 18:22
     */
    @Bean
    public LocalDateTimeSerializer localDateTimeDeserializer() {
        return new LocalDateTimeSerializer(DateTimeFormatter.ofPattern(pattern));
    }

    @Primary
    @Bean
    public ObjectMapper objectMapper(Jackson2ObjectMapperBuilder builder) {
        ObjectMapper objectMapper = builder.createXmlMapper(false).build();
        // 解决enum不匹配问题 默认值为false
        objectMapper.configure(DeserializationFeature.READ_UNKNOWN_ENUM_VALUES_AS_NULL, true);
        // 全局配置序列化返回 JSON 处理
        SimpleModule simpleModule = new SimpleModule();
        // 将使用String来序列化Long类型
        simpleModule.addSerializer(Long.class, ToStringSerializer.instance).addSerializer(Long.TYPE, ToStringSerializer.instance);
        // 将使用String来序列化BigDecimal类型
        simpleModule.addSerializer(BigDecimal.class, new BigDecimalSerializer());
        simpleModule.addSerializer(BigDecimal.class, new JsonSerializer<BigDecimal>() {
            @Override
            public void serialize(BigDecimal value, JsonGenerator gen, SerializerProvider serializers) throws IOException {
                if (value != null) {
                    gen.writeString(value.stripTrailingZeros().toPlainString());
                }
            }
        });
        //如果值为null时字段key还是否输出:ALWAYS(总是输出),NON_NULL(为null的不输出)
//		objectMapper.setSerializationInclusion(JsonInclude.Include.ALWAYS);
//		objectMapper.getSerializerProvider().setNullValueSerializer(new JsonSerializer<Object>() {
//			@Override
//			public void serialize(Object o, JsonGenerator gen, SerializerProvider serializerProvider) throws IOException {
//				String fieldName = gen.getOutputContext().getCurrentName();
//				try {
//					//反射获取字段类型
//					Field field = gen.getCurrentValue().getClass().getDeclaredField(fieldName);
//					if (Objects.equals(field.getType(), String.class)) {
//						//字符串型空值""
//						gen.writeString("");
//						return;
//					} else if (Objects.equals(field.getType(), List.class)) {
//						//列表型空值返回[]
//						gen.writeStartArray();
//						gen.writeEndArray();
//						return;
//					} else if (Objects.equals(field.getType(), Map.class)) {
//						//map型空值返回{}
//						gen.writeStartObject();
//						gen.writeEndObject();
//						return;
//					}
//				} catch (NoSuchFieldException e) {
//				}
//				//默认返回""
//				gen.writeString("");
//			}
//		});

        objectMapper.registerModule(simpleModule);
        return objectMapper;
    }

}
